/**
 * saas接口相关
 * @author ytl
 */

import Qs from 'qs';
import axios from 'axios';
import {INTERACE_SAAS_BASE_URL} from 'components/api/index-local';
import {setSessionStorageItem, getSessionStorageItem, getLocalStorageItem, setLocalStorageItem} from 'components/api/utils';
import {getUserIdentity} from 'components/api/interface-hhy';

// businessType 堂食自助(（扫码点餐）):TS，秒吃(预约堂食)：MC，自提（预约自提）：ZT，外送（预约外送）：WS，
export const BUSINESS_TYPE_TS = 'TS';
export const BUSINESS_TYPE_MC = 'MC';
export const BUSINESS_TYPE_ZT = 'ZT';
export const BUSINESS_TYPE_WS = 'WS';

// 是否需要打包
export const NEED_PACKAGE_YES = 'YES';
export const NEED_PACKAGE_NO = 'NO';

// 字典 dictGroup
export const DICT_GROUP_BUSINESS_TYPE = 'BUSINESS_TYPE';

// 业务开通状态 OPEN/NO
export const BUSINESS_TYPE_STATUS_OPEN = 'OPEN';
export const BUSINESS_TYPE_STATUS_NO = 'NO';

// 菜例要求是否必填
export const FOOD_SETTING_MUST_YES = 'YES';
export const FOOD_SETTING_MUST_NO = 'NO';

/**
 * 创建axios实例
 * @return {axios}
 */
export function createHttp() {
  let $httpSaas = axios.create({
    baseURL: INTERACE_SAAS_BASE_URL,
    transformRequest: [function (data) {
      data = Qs.stringify(data);
      return data;
    }],
    headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    timeout: 60000
  });

// 添加一个响应拦截器
  $httpSaas.interceptors.response.use(res => {
    return res.data;
  }, err => {
    console.log(err);
    return Promise.reject(err);
  });
  return $httpSaas;
}

/**
 * 查询字段数据接口
 * @param dictGroup 字典组编码
 * @param dictCode 字典详情编码 ''表示查询所有
 * @return {Promise}
 */
export function getDictItems (dictGroup, dictCode = '') {
  let dictItems = getLocalStorageItem('dictItems') ? getLocalStorageItem('dictItems') : {};
  if (!dictItems || !dictItems[dictGroup] || (dictCode !== '' && !dictItems[dictGroup][dictCode])) {
    let url = '/dict-group/' + dictGroup + '/dict-item';
    let $httpSaas = createHttp();
    $httpSaas.interceptors.response.use(res => {
      dictItems[dictGroup] = {};
      res.forEach(row => {
        let itemDictCode = row.reDictItem.dictCode;
        dictItems[dictGroup][itemDictCode] = row.reDictItem;
      });
      setLocalStorageItem('dictItems', dictItems, 86400);
      return dictCode ? row.reDictItem : dictItems[dictGroup];
    });
    return $httpSaas.get(url);
  }

  if (dictCode === '') {
    return Promise.resolve(dictItems[dictGroup]);
  }

  return Promise.resolve(dictItems[dictGroup][dictCode]);
}
/**
 * GET /v1/branch/{branchId}/mc-setting
 * GET /v1/branch/{branchId}/ts-setting
 * GET /v1/branch/{branchId}/ws-setting
 * GET /v1/branch/{branchId}/zt-setting
 * 获取业务设置信息
 * @return {Promise}
 */
export function getBusinessSetting() {
  let setting = getSessionStorageItem('businessSetting');
  if (setting) {
    return Promise.resolve(setting);
  }
  let userIdentity = getUserIdentity();
  let businessType = userIdentity.businessType.toLocaleLowerCase();
  let url = '/branch/' + userIdentity.branchId + '/' + businessType + '-setting';
  let $httpSaas = createHttp();
  $httpSaas.interceptors.response.use(data => {
    setSessionStorageItem('businessSetting', data);
    return data;
  });
  return $httpSaas.get(url);
}

/**
 * /food-catalog/branch-id/{branchId}/customer-level/{customerLevel}/business-type/{businessType}/business-hours/{businessHours}
 * 获取菜例列表
 * @param businessHours 扫码点餐无需传递；
 * @return {Promise}
 */
export function getGoodsList(businessHours = 0) {
  let userIdentity = getUserIdentity();
  let url = '/food-catalog/branch-id/' + userIdentity.branchId +
    '/customer-level/' + userIdentity.levelType +
    '/business-type/' + userIdentity.businessType +
    '/business-hours/' + businessHours;
  let $httpSaas = createHttp();
  return $httpSaas.get(url);
}

/**
 * GET /setting/branch/{branchId}/set-template/{settingTypes}/page/{page}/page-size/{pageSize}
 * 获取忌口列表
 * @return {Promise}
 */
export function getJikouList () {
  let branchId = getUserIdentity('branchId');
  let url = '/setting/branch/' + branchId +
    '/set-template/JIKOU/page/1/page-size/100';
  let $httpSaas = createHttp();
  return $httpSaas.get(url);
}

/**
 * 订餐时间列表
 * GET /v1/branch/{id}/business-type/{type}/time-list
 * @param {Number} branchId
 * @return {Promise}
 */
export function getBranchTimeList (branchId) {
  let userIdentity = getUserIdentity();
  let url = '/branch/' + branchId + '/business-type/' + userIdentity.businessType + '/time-list';
  let $http = createHttp();
  return $http.get(url);
}

/**
 * GET /v1/branch/{branchId}/business-info
 */
export function getBranchBusinessInfo () {
  let url = '/branch/' + getUserIdentity().branchId + '/business-info';
  let $http = createHttp();
  return $http.get(url);
}
/**
* 忌口消息
* GET /v1/setting/branch/{branchId}/setting-option
* @param {Number} branchId
* @return {Promise}
  */
export function getSettingOption (branchId) {
  let userIdentity = getUserIdentity();
  let url = '/setting/branch/' + userIdentity.branchId + '/setting-option';
  let $http = createHttp();
  return $http.get(url);
}
